package mall.repository;

import mall.core.jdbc.Repository;
import mall.entity.Book;
import org.springframework.jdbc.core.BeanPropertyRowMapper;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xf07b1
 * @wechat xf07b1
 * @description
 */
public class BookRepository extends Repository {

    /**
     * 新增
     */
    public int insert(Book book) {
        String sql = "insert into book(book_name) values(?)";
        return jdbcTemplate.update(sql, book.getBookName());
    }

    /**
     * 删除
     */
    public int deleteById(int id) {
        String sql = "delete from book where id = ?";
        return jdbcTemplate.update(sql, id);
    }

    /**
     * 修改
     */
    public int update(Book book) {
        String sql = "update book set book_name = ? where id = ?";
        return jdbcTemplate.update(sql, book.getBookName(), book.getId());
    }

    /**
     * 查询单个
     */
    public Book selectById(int id) {
        String sql = "select * from book where id = ?";
        List<Book> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Book.class), id);
        return list.isEmpty() ? null : list.get(0);
    }

    /**
     * 查询所有
     */
    public List<Book> selectList() {
         return jdbcTemplate.query("select * from book", new BeanPropertyRowMapper<>(Book.class));
    }

    /**
     * 分页查询
     */
    public List<Book> selectList(Book book, Integer offset, Integer size) {
        StringBuilder sb = new StringBuilder("select * from book where 1=1 ");
        List<Object> params = new ArrayList<>();

        if (book.getId() != null) {
            sb.append(" and id = ?");
            params.add(book.getId());
        }
        if (book.getBookName() != null) {
            sb.append(" and book_name = ?");
            params.add(book.getBookName());
        }


        sb.append(" limit ?, ?");
        params.add(offset);
        params.add(size);

        return jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(Book.class), params.toArray());
    }

    /**
     * 查询数量
     */
    public Integer count(Book book) {
        StringBuilder sb = new StringBuilder("select count(*) from book where 1=1 ");
        List<Object> params = new ArrayList<>();

        if (book.getId() != null) {
            sb.append(" and id = ?");
            params.add(book.getId());
        }
        if (book.getBookName() != null) {
            sb.append(" and book_name = ?");
            params.add(book.getBookName());
        }


        return jdbcTemplate.queryForObject(sb.toString(), Integer.class, params.toArray());
    }

}
